import axios from 'axios'
import qs from 'qs'
import { Toast } from 'vant'

const service = axios.create({
  timeout: 60000
})

if (import.meta.env.MODE.trim() === 'development') {
  service.defaults.baseURL = '/apis/virtualhuman/serverApi'
} else {
  service.defaults.baseURL = '/virtualhuman2/serverApi'
}

service.defaults.headers['Content-Type'] =
  'application/x-www-form-urlencoded;charset=UTF-8'

// request interceptor
service.interceptors.request.use(
  (config) => {
    if (config.showLoading) {
      Toast.loading({
        duration: 0,
        forbidClick: true
      })
    }
    if (
      config.headers['Content-Type'] !== 'multipart/form-data'
    ) {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    if (response.config.showLoading) {
      Toast.clear()
    }
    const res = response.data
    if (
      (response.config.url === '/oauth/token' && res.access_token)
    ) {
      return Promise.resolve(res)
    } else if (res.code === 200) {
      return Promise.resolve(res.data)
    } else {
      return Promise.reject(res.error_description || res.msg || '接口报错')
    }
  },
  (error) => {
    if (error.config.showLoading) {
      Toast.clear()
    }
    return Promise.reject(
      error.response.data.error_description ||
        error.response.data.error ||
        error.message
    )
  }
)

export default service
